package com.caishi.lkx.common.message;

import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class MessageServiceImpl implements IMessageService {

    @Resource
    private MongoTemplate template;

    @Resource
    private MessageMongoRepository messageMongoRepository;

    @Override
    public MessageModel saveMessage(MessageModel model) {
        return messageMongoRepository.insert(model);
    }

    @Override
    public List<MessageModel> list(String userId, int current, int size, Long maxTimestamp) {
        Criteria criteria = Criteria.where("userId").is(userId);
        if (maxTimestamp != null) {
            criteria.and("createdTime").gt(maxTimestamp);
        }
        return template.query(MessageModel.class).matching(
                Query.query(criteria).skip((long) (current - 1) * size).limit(size).with(Sort.by(Sort.Order.asc("haveRead"), Sort.Order.desc("id")))
        ).all();
    }


    @Override
    public List<MessageModel> list(String userId, int current, int size) {
        return list(userId, current, size, null);
    }

    @Override
    public void readMessage(String id) {
        template.upsert(Query.query(Criteria.where("_id").is(new ObjectId(id))),
                Update.update("haveRead", true).addToSet("readTime", LocalDateTime.now()),
                MessageModel.class);
    }

    @Override
    public void readAllMessage(String userId) {
        template.updateMulti(Query.query(Criteria.where("userId").is(userId).and("haveRead").is(false)), Update.update("haveRead", true), MessageModel.class);
    }
}
